﻿using Humanizer;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using WXWorkSvc.Common.Extensions;
using WXWorkSvc.Models;

namespace WXWorkSvc.Controllers;

[Route("api/[controller]")]
[ApiController]
public class PrivateMsgController : ControllerBase
{
    private readonly Cryptography _Cryptography;
    private readonly WXWorkPrivate _WXWorkPrivate;
    public PrivateMsgController(Cryptography cryptography, WXWorkPrivate wXWork)
    {
        _Cryptography = cryptography;
        _WXWorkPrivate = wXWork;
    }
    [HttpPost("text")]
    public async Task<IActionResult> TextAsync(string msg_signature, string timestamp, string nonce)
    {
        var sr = new StreamReader(Request.Body);
        var bd = await sr.ReadToEndAsync();
        if (!_Cryptography.VerifyURL<RequestPrivateMessage>(msg_signature, timestamp, nonce, bd, out var req))
            return BadRequest();
        await _WXWorkPrivate.SendTextMessageAsync(req!.AgentId, req.UserIds, req.Message);
        return Ok();
    }
    [HttpPost("md")]
    public async Task<IActionResult> MDAsync(string msg_signature, string timestamp, string nonce)
    {
        var sr = new StreamReader(Request.Body);
        var bd = await sr.ReadToEndAsync();
        if (!_Cryptography.VerifyURL<RequestPrivateMessage>(msg_signature, timestamp, nonce, bd, out var req))
            return BadRequest();
        await _WXWorkPrivate.SendMDMessageAsync(req!.AgentId, req.UserIds, req.Message);
        return Ok();
    }

}
